package cn.itcast.star.graph.core.interceptor;

import cn.hutool.json.JSONUtil;
import cn.itcast.star.graph.core.dto.common.Result;
import cn.itcast.star.graph.core.dto.common.ResultCode;
import cn.itcast.star.graph.core.pojo.User;
import cn.itcast.star.graph.core.utils.JwtUtils;
import cn.itcast.star.graph.core.utils.UserUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jodd.util.StringUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtil.isEmpty(header)) {
            writeErrorMessage(response);
            return false;
        }

        // 校验令牌
        if (!JwtUtils.verify(header)) {
            writeErrorMessage(response);
            return false;
        }

        // 将用户信息存入线程变量中
        User user = JwtUtils.getUser(header);
        UserUtils.set(user);
        return true;
    }

    private void writeErrorMessage(HttpServletResponse response) {
        // 设置状态码及响应头
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        // 设置响应体内容
        try (PrintWriter writer = response.getWriter()){
            Result<Object> result = Result.failed(ResultCode.ACCESS_UNAUTHORIZED);
            writer.println(JSONUtil.toJsonStr(result));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtils.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
